import React,{useEffect,useState,useRef} from 'react';
import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    View,
    Text, TouchableOpacity, DeviceEventEmitter,
    StatusBar, Image, TouchableWithoutFeedback, RefreshControl,
} from 'react-native';
import RefreshFlatList, {RefreshState} from '../../widgets/RefreshFlatList';
import {useStores} from '../../store';
import {observer} from 'mobx-react';
import screen from '../../utils/screen';
import ShadowBoxView from '../../widgets/ShadowBoxView';
import Images from '../../images/Images';
import colors from '../../utils/colors';
import {AppModal} from '../../widgets/modal';
import RequestUtil from '../../utils/RequestUtil';
import Api from '../../utils/Api';
import Constants from '../../utils/Constants';
import {cutZero, numMulti, setTextThousand} from '../../utils/common';
import {LGBtn} from '../../widgets/buttons';
import InvestDialog from '../../components/InvestDialog';
import AppEvent from '../../utils/AppEvent';

const pageSize  = 10
export default observer( ({navigation})=>{

    const {userStore} = useStores()

    const [data,setData] = useState([])
    const [alldata,setAllata] = useState(null)
    const [page,setPage] = useState(1)
    const [refreshState,setRefreshState] = useState(RefreshState.Idle)
    const investDialog = useRef()

    useEffect(()=>{
        console.log(userStore.userInfo)
        getData()

       /* const emitter = DeviceEventEmitter.addListener(AppEvent.invest_update,()=>{
            getData()
        })

        return ()=>{
            emitter && emitter.remove()
        }*/

    },[])

    const getData = ()=>{
        AppModal.showLoading()

        RequestUtil.get(Api.investment).then(res=>{

            AppModal.hideTip()
            let list = res.data.products
            console.log('investment ',res.data)
            //更新用户余额
            userStore.setUser(null,{balance:res.data.current_balance})
            if(!list.length){
                setRefreshState(RefreshState.EmptyData)
                return
            }

            if(pageSize * page > list.length){
                setData(list)
            }else{
                let newlist = []
                for(let i = 0;i < pageSize * page;i++){
                    if(list[i]){
                        newlist.push(list[i])
                    }
                }
                console.log('new list',newlist)
                setData(newlist)
            }
            setAllata(res.data)
            if(!userStore.userInfo.balance){
                userStore.setUser(null,{
                    balance:res.data.balance,
                })
            }
        },error=>{
            console.log(error)
            AppModal.hideTip()
            AppModal.showTip(error.msg)
        })
    }

    useEffect(()=>{
        if(!alldata) return
        if(page === 1) return;

        if(page * pageSize < alldata.products.length){
            setRefreshState(RefreshState.FooterRefreshing)
            setTimeout(()=>{
                let newlist = []
                let startIndex = data.length
                for(let i = startIndex; i < page * pageSize;i++){
                    newlist.push(alldata.products[i])
                }
                setData(data.concat(newlist))
                setRefreshState(RefreshState.Idle)
            },1000)
        }else{
            setRefreshState(RefreshState.NoMoreData)
        }

    },[page])

    const renderHeader = ()=>{


        const {nickName} = userStore.userInfo

        let nameStr = nickName;
        if(nickName.length > 10) {
            nameStr = nickName.substring(0,10) + "...";
        }

        let defaultData = {
            interest_amount:0,invest_amount:0,total_order:0
        }
        const {interest_amount,invest_amount,total_order} = alldata ? alldata.my_product : defaultData

        const  renderColumnItem = (title,value,showCurrency = true)=>{
            return (
                <View style={{alignItems:'center',}}>
                    <Text style={{fontSize:13,color:'#000',marginBottom:screen.PIXEL_10}}>{title}</Text>
                    {showCurrency ? (
                        <Text style={{color:'#FF7012',fontSize:13}}>{Constants.appsymbol}
                            <Text style={{fontSize:19}}>{' ' + setTextThousand(value) }</Text>
                        </Text>
                    ):(
                        <Text style={{color:'#FF7012',fontSize:19}}>{value}</Text>
                    )}

                </View>
            )
        }

        return (
            <View style={styles.header}>

                <View style={{flexDirection: 'row',justifyContent: 'space-between',alignItems:'center'}}>

                    <Text style={ {color:'#000',fontSize:16,fontWeight:'bold'}}>{'Hi,'}{nameStr}</Text>

                    <TouchableOpacity
                        style={{flexDirection: 'row',alignItems:'center'}}
                        onPress={()=>{
                            navigation.navigate('MyInvestment')
                        }}
                    >
                        <Text style={{fontSize:16,color:'#007267'}}>{Constants.account.view_all}</Text>
                        <Image source={Images.right}
                               resizeMode={'contain'}
                               style={{width:screen.PIXEL_30,height:screen.PIXEL_30}}/>
                    </TouchableOpacity>

                </View>

                <View style={{flexDirection: 'row',justifyContent: 'space-between',marginTop:screen.PIXEL_10}}>
                    {renderColumnItem(Constants.account.current_orders,total_order,false)}
                    {renderColumnItem(Constants.account.total_investment,cutZero(invest_amount))}
                    {renderColumnItem(Constants.account.daily_profit,interest_amount)}
                </View>

            </View>
        )
    }

    const renderItem = ({item,index})=>{
        // console.log(item)

        return (
            <View style={{padding:screen.PIXEL_40,paddingVertical:screen.PIXEL_20}}>
                <ShadowBoxView

                    shadowOption={{
                        radius:screen.PIXEL_40,
                        color:'#000',
                        x:0,
                        y:0,
                        border:5
                    }}
                >
                    <View style={{justifyContent:'space-between',backgroundColor: '#fff',
                        padding:screen.PIXEL_40,borderRadius:screen.PIXEL_40,flexDirection:'row'
                    }}>

                        <View style={{flex:1}}>
                            <Text style={{fontSize:12,color:'#000'}}>{Constants.account.starting_amount}</Text>
                            <Text style={{fontSize:30,color:'#FF7012'}}>{setTextThousand(item.starting_amount)}</Text>
                            <Text style={{fontSize:12,color:'#000'}}>{Constants.account.interest}</Text>
                            <Text style={{fontSize:15,color:'#FF7012'}}>{numMulti(item.interest_rate,100) + '%'}</Text>
                            <Text style={{fontSize:12,color:'#000',textAlign:'right'}}>({numMulti(item.interest_rate_daily,100) + '% ' + Constants.vip.per_day} )</Text>
                        </View>

                        <View style={{marginLeft:screen.PIXEL_30}}>

                            <View style={{flex:1}}>
                                <Text style={{fontSize:12,color:'#000'}}>{Constants.account.cycle}</Text>
                                <Text style={{fontSize:15,color:'#FF7012'}}>{item.cycle + ' days'}</Text>
                            </View>

                            <LGBtn
                                title={Constants.account.invest}
                                style={{width:screen.PIXEL_230,height:screen.PIXEL_90}}
                                onPress={()=>{
                                    let data = {...item,balance:alldata.current_balance}
                                    investDialog.current.show(data,()=>{
                                        investDialog.current.hideDialog()
                                        getData()
                                    })
                                }}
                            />

                        </View>

                    </View>

                </ShadowBoxView>
            </View>
        )
    }

    return (
        <View style={styles.container}>
            <View style={styles.content}>
                {renderHeader()}
                {
                    alldata && (
                        <RefreshFlatList
                            data={data}
                            renderItem={renderItem}
                            refreshState={refreshState}
                            onFooterRefresh={()=>{
                                setPage(page + 1)
                            }}
                            onHeaderRefresh={()=>{
                                setPage(1)
                                getData()
                            }}


                        />
                    )
                }
            </View>


            <InvestDialog ref={investDialog} navigation={navigation}/>
        </View>
    )
})

const styles= StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:colors.tabBgColor
    },
    content:{
        flex:1,backgroundColor: '#fff',
        borderBottomLeftRadius:screen.PIXEL_110,
        borderBottomRightRadius:screen.PIXEL_110,
        paddingTop:screen.statusBarHeight
    },header:{
        paddingHorizontal:screen.PIXEL_60,
        marginVertical:screen.PIXEL_10
    },
})
